<template>
  <div class="teacher-detail-container">
    <el-card shadow="hover" class="teacher-card" v-loading="loading">
      <!-- 教师基本信息 -->
      <div class="teacher-info" v-if="teacherData">
        <div class="avatar-section">
          <el-avatar :size="120" :src="teacherData.avatar || defaultAvatar" />
          <div class="teacher-name">{{ teacherData.teaName }}</div>
          <div class="teacher-id">教师ID: {{ teacherData.id }}</div>
        </div>
        
        <div class="info-section">
          <el-descriptions title="基本信息" :column="1" border>
            <el-descriptions-item label="用户ID">{{ teacherData.userId }}</el-descriptions-item>
            <el-descriptions-item label="教授课程数">{{ teacherCourses.length }}</el-descriptions-item>
            <el-descriptions-item label="教授班级数">{{ teacherClasses.length }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatTime(teacherData.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ formatTime(teacherData.updateTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      
      <!-- 选项卡 -->
      <el-tabs  class="teacher-tabs" >  
        <!-- 教授的课程 -->
        <el-tab-pane label="我的课程" name="courses">
          <el-table 
            :data="teacherCourses" 
            style="width: 100%" 
            v-loading="coursesLoading"
            @row-click="viewCourseDetail"
          >
            <el-table-column prop="courseName" label="课程名称" />
            <el-table-column prop="chapterCount" label="章节数" width="100" />
            <el-table-column prop="studentCount" label="学习人数" width="120" />
            <el-table-column prop="createTime" label="创建时间" width="180" />
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div v-if="error" class="error-message">
        <el-alert :title="error" type="error" show-icon />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { teacherApi } from '@/api/teacher'
import defaultAvatar from '@/assets/logo.png'
import { formatDateTime } from '@/utils/date'

const route = useRoute()
const router = useRouter()

const teacherId = ref(route.params.id)
const activeTab = ref('classes')
const loading = ref(true)
const classesLoading = ref(false)
const coursesLoading = ref(false)
const error = ref(null)

// 教师数据
const teacherData = ref(null)
const teacherClasses = ref([])
const teacherCourses = ref([])

// 获取教师基本信息
const fetchTeacherDetail = async () => {
  try {
    loading.value = true
    const response = await teacherApi.getTeacherById(teacherId.value)
    
    if (!response || !response.id) {
      throw new Error('教师数据格式不正确')
    }
    
    teacherData.value = {
      id: response.id,
      userId: response.userId,
      teaName: response.teaName || '未知教师',
      createTime: response.createTime,
      updateTime: response.updateTime,
      avatar: response.avatar
    }
  } catch (err) {
    error.value = `获取教师信息失败: ${err.message}`
    console.error('教师信息错误:', err)
  } finally {
    loading.value = false
  }
}

// 获取教师班级数据
const fetchTeacherClasses = async () => {
  try {
    classesLoading.value = true
    const response = await teacherApi.getTeacherClasses(teacherId.value)
    
    teacherClasses.value = Array.isArray(response) 
      ? response.map(item => ({
          id: item.id,
          className: item.className || '未命名班级',
          studentCount: item.studentCount || 0,
          createTime: formatDateTime(item.createTime)
        }))
      : []
  } catch (err) {
    error.value = `获取班级信息失败: ${err.message}`
    console.error('班级数据错误:', err)
  } finally {
    classesLoading.value = false
  }
}

// 获取教师课程数据
const fetchTeacherCourses = async () => {
  try {
    coursesLoading.value = true
    const response = await teacherApi.getTeacherCourses(teacherId.value)
    
    teacherCourses.value = Array.isArray(response)
      ? response.map(item => ({
          id: item.id,
          courseName: item.courseName || '未命名课程',
          chapterCount: item.chapters?.length || 0, // 从返回的章节数组获取数量
          studentCount: item.students?.length || 0, // 从返回的学生数组获取数量
          createTime: formatDateTime(item.createTime)
        }))
      : []
  } catch (err) {
    error.value = `获取课程信息失败: ${err.message}`
    console.error('课程数据错误:', err)
  } finally {
    coursesLoading.value = false
  }
}

// 格式化时间显示
const formatTime = (timestamp) => {
  return timestamp ? formatDateTime(timestamp) : '未知'
}

// 查看班级详情
const viewClassDetail = (row) => {
  router.push(`/class/${row.id}`)
}

// 查看课程详情
const viewCourseDetail = (row) => {
  router.push({
    path: `/course/${row.id}`,
    query: { teacherId: teacherId.value }
  })
}

onMounted(async () => {
  await fetchTeacherDetail()
  await Promise.all([
    fetchTeacherClasses(),
    fetchTeacherCourses()
  ])
})
</script>

<style scoped>
.teacher-detail-container {
  padding: 20px;
}

.teacher-card {
  min-height: 500px;
}

.teacher-info {
  display: flex;
  margin-bottom: 20px;
}

.avatar-section {
  width: 200px;
  text-align: center;
  padding: 20px;
}

.teacher-name {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
}

.teacher-id {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.info-section {
  flex: 1;
  padding: 20px;
}

.teacher-tabs {
  margin-top: 20px;
}

.error-message {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .teacher-info {
    flex-direction: column;
  }
  
  .avatar-section {
    width: 100%;
    margin-bottom: 20px;
  }
}

/* 添加表格行点击效果 */
.el-table__row {
  cursor: pointer;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}
</style>